package com.sh.cloudrender.infrastructure.configuration;

import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.JSON;
import io.kubernetes.client.openapi.apis.AppsV1Api;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.apis.CustomObjectsApi;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.Config;
import io.kubernetes.client.util.KubeConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.io.*;
import java.nio.file.Files;

@Slf4j
@Configuration
public class KubeConfiguration {

    @Value("${kubernetes.config.path}")
    private String kubeConfigPath;

    @Bean
    public ApiClient apiClient() {
        ApiClient client = null;
        try {
            // 尝试从外部的kubeconfig文件加载配置
//            InputStream inputStream = KubeConfiguration.class.getResourceAsStream(kubeConfigPath);
            File file = new File(kubeConfigPath);
            if (!file.exists() || !file.isFile()) {
                throw new IOException("Kubeconfig file not found: " + kubeConfigPath);
            }
            InputStream inputStream = Files.newInputStream(file.toPath());
            if (inputStream != null) {
                Reader input = new InputStreamReader(inputStream);
                KubeConfig kubeConfig = KubeConfig.loadKubeConfig(input);
                client = ClientBuilder.kubeconfig(kubeConfig).build();
                log.info("Kubernetes API URL: " + client.getBasePath());
                log.info("Successfully loaded Kubernetes configuration from external file: " + kubeConfigPath);
            } else {
                throw new IOException("Kubeconfig file not found: " + kubeConfigPath);
            }

        } catch (IOException e) {
            log.warn("Failed to load kubeconfig from external file, trying in-cluster configuration", e);
            try {
                // 如果外部配置失败，尝试从集群内部加载配置
                client = Config.fromCluster();
                log.info("Successfully loaded Kubernetes configuration from in-cluster");
            } catch (IOException ex) {
                log.error("Failed to load in-cluster configuration", ex);
                throw new RuntimeException(ex);
            }
        }

        io.kubernetes.client.openapi.Configuration.setDefaultApiClient(client);
        return client;
    }

    @Bean
    @DependsOn("apiClient")
    public CoreV1Api coreV1Api(ApiClient apiClient) {
        CoreV1Api api = new CoreV1Api(apiClient);
        return api;
    }

    @Bean
    @DependsOn("apiClient")
    public AppsV1Api appsV1Api(ApiClient apiClient){
        AppsV1Api appsV1Api = new AppsV1Api(apiClient);
        return appsV1Api;
    }

    @Bean
    @DependsOn("apiClient")
    public CustomObjectsApi customObjectsApi(ApiClient apiClient){
        CustomObjectsApi api = new CustomObjectsApi(apiClient);
        return api;
    }
}
